from flask import Blueprint, request, render_template, jsonify, session
from sqlalchemy import or_

from config import db
from models.models import Goods, ShopThing, History, User
from utils.utils import result, get_order_num, get_now_data_time

goods_service = Blueprint('good_service', __name__)


@goods_service.before_request
def session_checker():
    if 'user_id' not in session:
        return render_template('401.html')


# 添加商品
@goods_service.route('/goods/good/add', methods=['GET', 'POST'])
def goods_good_add():
    if request.method == "POST":
        form = request.form
        image = request.files["image"]
        save_path = "./static/goods/" + get_order_num() + image.filename
        image.save(save_path)
        data = {
            "name": form["name"],
            "goods_type": form["goods_type"],
            "goods_price": form["goods_price"],
            "goods_outline": form["goods_outline"],
            "goods_photo": save_path,
        }
        goods = Goods(**data)
        try:
            db.session.add(goods)
            db.session.commit()
            return result(200, "添加商品信息成功！")
        except:
            return result(400, "商品信息已存在！")
    else:
        return render_template('购物车.html')


# 删除商品
@goods_service.route("/goods/good/delete", methods=["DELETE"])
def goods_delete():
    name = request.form["name"]
    ok = Goods.query.filter_by(name=name).delete()
    db.session.commit()
    if ok == 0:
        return result(400, "没有找到该商品，删除失败！")
    else:
        return result(200, "删除商品成功！")


# 查询所有商品信息
@goods_service.route("/goods/goods", methods=['GET', 'POST'])
def goods():
    if request.method == "GET":
        nums = Goods.query.count()
        return result(200, {"nums": nums})


# 通过名称获取一条商品信息 ，后面改成模糊查询
@goods_service.route("/goods/get/good", methods=['GET', 'POST'])
def get_good():
    if request.method == "GET":
        pass
    name = request.form['name']
    good = Goods.query.filter_by(name=name).first()
    data = {
        "id": good.id,
        "name": good.name,
        "goods_type": good.goods_type,
        "goods_price": good.goods_price,
        "goods_outline": good.goods_outline,
        "goods_photo": good.goods_photo
    }
    return result(200, data)


# 通过名称id获取一条商品信息
@goods_service.route("/get/good/<int:_id>")
def get_good_by_id(_id):
    user_id = session.get("user_id")
    good = Goods.query.filter_by(id=_id).first()
    history = History(
        user_id=user_id,
        good_id=good.id,
        type=good.type,
        createTime=get_now_data_time()
    )
    db.session.add(history)
    db.session.commit()
    data = {
        'id': good.id,
        'name': good.name,
        'type': good.type,
        'price': good.price,
        'outline': good.outline,
        'img_url': good.img_url,
        'link_url': good.link_url
    }
    return jsonify({'data': data})


@goods_service.route("/get/good/detail/<int:_id>")
def get_good_detail(_id):
    return render_template('good_details.html')


@goods_service.route("/good")
def goods_type():
    types = Goods.query.all()
    data = []
    for _type in types:
        value = {
            'id': _type.id,
            'img': _type.img,
            'name': _type.name,
            'price': _type.price
        }
        data.append(value)
    return jsonify({
        'code': 0,
        'msg': '',
        'data': data
    })


# 在index界面点击面包屑标签是时加载的表格
@goods_service.route("/shop/thing/<int:_id>")
def shop_thing(_id):
    if _id == 0:
        types = Goods.query.all()
    else:
        types = Goods.query.filter_by(type=_id)
    data = []
    for _type in types:
        value = {
            'good_id': _type.id,
            'name': _type.name,
            'price': _type.price,
            'type': _type.type,
            'outline': _type.outline,
            'img_url': _type.img_url,
            'link_url': _type.link_url
        }
        data.append(value)
    return jsonify({'data': data})


@goods_service.route("/goodthing")
def goods_thing():
    types = ShopThing.query.all()
    data = []
    for _type in types:
        value = {
            'good_id': _type.id,
            'name': _type.name,
            'price': _type.price,
            'type': _type.type,
            'outline': _type.outline,
            'img_url': _type.img_url,
            'link_url': _type.link_url
        }
        data.append(value)
    return jsonify({'data': data})


@goods_service.route("/search/good")
def search_good():
    page = int(request.args.get("page", 1))
    limit = int(request.args.get("limit", 10))
    keyword = request.args.get("keyword", "")

    query = db.session.query(Goods)

    if keyword:
        query = query.filter(
            or_(
                Goods.name.like(f"%{keyword}%"),
                Goods.outline.like(f"%{keyword}%")
            )
        )

    types = query.paginate(page=page, per_page=limit)
    data = []
    for _type in types.items:
        value = {
            'good_id': _type.id,
            'name': _type.name,
            'price': _type.price,
            'type': _type.type,
            'outline': _type.outline,
            'img_url': _type.img_url,
            'link_url': _type.link_url
        }
        data.append(value)

    return jsonify({'data': data, 'code': 0, 'count': types.total})


@goods_service.route("/good/comment")
def good_comment():
    pass


